package anli2;

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        List<Student> allStudent = getStudentsList("anli2/allStu.txt");
        System.out.println("读取到 " + allStudent.size()+ " 条数据，请选择排序的方式输出: 0 默认 1根据\"学号\" ........");
        Scanner scanner= new Scanner(System.in);
        int orderType  = scanner.nextInt();
        showStudent(allStudent, orderType);

    }

    /**
     * 直接打印学生数据
     *
     * @param students  学生集合
     * @param orderType 0 默认输出  1 学号  2 年龄 3 性别
     */
    private static void showStudent(List<Student> students, int orderType) {
        if (students != null && students.size() > 0) {
//           orderType:  1 2 3 的时候需要排序输出
            if(orderType == 1 || orderType == 2 || orderType == 3 ){
                Comparator<Student> comparator = new Comparator<>() {
                    @Override
                    public int compare(Student s1, Student s2) {
                        int rs = 0;
                        switch (orderType) {
                            case 1:
                                rs = s1.getStuNo().compareTo(s2.getStuNo());
                                break;
                            case 2:
                                rs = s1.getAge() - s2.getAge();
                                break;
                            case 3:
                                rs = s1.getSex().compareTo(s2.getSex());
                                break;
                        }
                        return rs;
                    }
                };
                Collections.sort(students, comparator);
            }
            System.out.println("================ 以下按 " + (orderType==1?"学号":(orderType==2?"年龄":"性别")) + " 方式排序输出 ================");
            for (Student student : students) {
                System.out.println(student);
            }
        }
    }

    private static List<Student> getStudentsList(String path) {
        Scanner scanner = new Scanner(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
        List<Student> allStudent = new ArrayList<>();
        int lineNum = 0;
        while (scanner.hasNextLine()) {
            String eachLine = scanner.nextLine();
            lineNum++;
            if (eachLine != null && eachLine.trim().length() > 0) {
                String[] split = eachLine.split(",");
                if (split.length != 4) {
                    throw new RuntimeException("数据格式不正确， 行号:" + lineNum);
                }
                Student student = new Student().setName(split[0]).setStuNo(split[1]).setAge(Integer.parseInt(split[3].trim())).setSex(split[2]);
                allStudent.add(student);
            }
        }
        return allStudent;
    }
}
